/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CheckOutGUI.java
 *
 * Created on 29/06/2010, 10:34:53 PM
 */

package frontera;
import entidad.Clientes;
import entidad.Movimientos;
import entidad.MovimientoDetalles;
import control.ClientesCTR;
import control.DetallesCTR;
import control.CheckOutCTR;

import control.FacturaCTR;
import entidad.Factura;
import java.awt.Dimension;
import java.awt.Panel;
import java.util.Date;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Juan Felipe
 */
public class CheckOutGUI extends javax.swing.JPanel {
    ClientesCTR controlC = new ClientesCTR();
    DetallesCTR controlD = new DetallesCTR();
    CheckOutCTR _control_checkout = new CheckOutCTR();

    FacturaGUI _factura_gui = new FacturaGUI();
    FacturaCTR _factura_ctr = new FacturaCTR();

    JDialog    _container_factura = new JDialog();

    Movimientos movimiento;//Almacena el movimiento del usuario seleccionado

    /** Creates new form CheckOutGUI */
    public CheckOutGUI(){
        initComponents();
        fechaSalida.setText(new Date().toString());
    }

    /**
     * buscarCliente
     * Busca un cliente y visualiza el nombre en la interfaz
     */
    private void buscarCliente(){
        Clientes c = controlC.validarCheckInCliente(Integer.parseInt(documento.getText()));
        if(c!=null){
            movimiento = controlD.getMovimientoByCC(c.getCedula());//Obtengo el movimiento activo del Cliente
            if(movimiento != null){
                nombreCliente.setText(c.getNombre());
                fechaEntrada.setText(movimiento.getFechaIni().toString());
                generarTotalFactura(movimiento);
                llenarGrilla();
            }else JOptionPane.showMessageDialog(this, "No se encontró un CheckIn para este cliente.");
        }else{
            JOptionPane.showMessageDialog(this, "El cliente No se encuentra registrado en el Hotel.");
        }
    }

    /**
     * generarTotalFactura
     * Calcula el valor total de los servicios
     * consumidos por un cliente.
     */
    private void generarTotalFactura(Movimientos m){
        int total = 0;
        for(MovimientoDetalles d : FramePrincipal1.sistema.getDetalles()){
            if(d.getMovimiento().equals(m)){
                total += d.getValorTotal();
                FramePrincipal1.sistema.getDetalles();
            }
        }
        valorTotal.setText(Integer.toString(total));
    }

    /**
     * llenarGrilla
     * Visualiza los consumos del Cliente
     */
    private void llenarGrilla(){
        DefaultTableModel _data = new DefaultTableModel(new Object []{"Servicio","Valor/Cantidad","Iva","Total" },0);
        int totalFactura = 0;
        String col1;
        String col2;
        int col3;
        int col4;
        for(MovimientoDetalles d : FramePrincipal1.sistema.getDetalles()){
            if(d.getMovimiento().equals(movimiento)){
                col1 = d.getServicios().getNombre();
                col2 = d.getServicios().getValorUnitario()+"/"+d.getServicios().getCantidad();
                col3 = d.getServicios().getIva();
                col4 = d.getValorTotal();
                totalFactura += d.getValorTotal();
                _data.addRow(new Object []{col1,col2,col3,col4}) ;
            }
            gridDetalles.setModel(_data);
            valorTotal.setText("$ "+Integer.toString(totalFactura));
        }
    }

    /**
     * generarFactura
     * Visualiza la factura con todos los detalles
     * del consumo del cliente para imprimirla
     */
    private void generarFactura(){
        //creacion de la factura
        if (movimiento != null){
            Factura _factura = new Factura();
            _factura.setId( _factura_ctr.get_max_factura()+1  );
            _factura.setFecha( new Date()  );
            _factura.get_movimiento().add(movimiento);
            _factura.setValor(  _control_checkout.generarTotalFactura(movimiento) );
            _factura.setEstado("Cancelada");
            FramePrincipal1.sistema.add_factura(_factura);
            
            _factura_gui.set_factura(_factura);
            _container_factura.setSize( new Dimension(600,550) );
            _container_factura.add(_factura_gui);
            _factura_gui.setVisible(true);

            _container_factura.setVisible(true);
            
            _factura_gui.tabular();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        nombreCliente = new javax.swing.JFormattedTextField();
        jLabel11 = new javax.swing.JLabel();
        documento = new javax.swing.JFormattedTextField();
        buscarCliente1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        guardarMovimiento = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        valorTotal = new javax.swing.JLabel();
        fechaSalida = new javax.swing.JTextField();
        fechaEntrada = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        gridDetalles = new javax.swing.JTable();

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 102, 51));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("CHECK-OUT");

        jLabel12.setText("Nombre del Cliente");

        nombreCliente.setEditable(false);

        jLabel11.setText("Documento Cliente");

        buscarCliente1.setText("Buscar");
        buscarCliente1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarCliente1ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel4.setForeground(new java.awt.Color(0, 102, 51));
        jLabel4.setText("Cuenta de Cobro");

        guardarMovimiento.setText("Generar Salida");
        guardarMovimiento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarMovimientoActionPerformed(evt);
            }
        });

        jLabel14.setText("Fecha de Entrada");

        jLabel9.setText("Fecha de Salida");

        jLabel16.setText("Valor Total Factura");

        valorTotal.setFont(new java.awt.Font("Tahoma", 1, 10));
        valorTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        valorTotal.setText("$ 0");

        fechaSalida.setEditable(false);
        fechaSalida.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        fechaEntrada.setEditable(false);
        fechaEntrada.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel2.setForeground(new java.awt.Color(0, 102, 51));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Sistema de Facturación Hotelero");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel7.setForeground(new java.awt.Color(0, 102, 51));
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel7.setText("La Potra Hotel Campestre");

        jButton1.setText("Imprimir Factura");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        gridDetalles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Servicio", "Cantidad", "Valor", "Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(gridDetalles);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nombreCliente, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(documento, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buscarCliente1))
                    .addComponent(jLabel4)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel16)
                        .addGap(18, 18, 18)
                        .addComponent(valorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addComponent(guardarMovimiento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel14)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fechaEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fechaSalida, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(documento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buscarCliente1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14)
                    .addComponent(fechaSalida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valorTotal)
                    .addComponent(jLabel16))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(guardarMovimiento)
                .addContainerGap(17, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void buscarCliente1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarCliente1ActionPerformed
        if(this._control_checkout.verificarCedula(this.documento.getText())){
            this.buscarCliente();
        }
        else{
            JOptionPane.showMessageDialog(this, "Verifique la cedula por favor.");
        }
}//GEN-LAST:event_buscarCliente1ActionPerformed

    private void guardarMovimientoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarMovimientoActionPerformed
        
}//GEN-LAST:event_guardarMovimientoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        generarFactura();
}                               


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscarCliente1;
    private javax.swing.JFormattedTextField documento;
    private javax.swing.JFormattedTextField fechaEntrada;
    private javax.swing.JTextField fechaSalida;
    private javax.swing.JTable gridDetalles;
    private javax.swing.JButton guardarMovimiento;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JFormattedTextField nombreCliente;
    private javax.swing.JLabel valorTotal;
    // End of variables declaration//GEN-END:variables

}
